package com.example.xianji.utils;

import java.io.File;

import com.example.xianji.constant.Constant;
import com.example.xianji.fragment.HomeFragment;
import com.example.xianji.utils.sp.PreferenceEngine;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;
/**
 * DownloadManager下载apk工具类
 * @author me
 *
 */
public class DownloadManagerUtils {
	// DownloadManager 来优化处理长时间的下载操作。DownloadManager 对后台下载，
	// 下载状态回调，断点续传，下载环境设置，下载文件的操作等都有很好的支持。

	public final static String SAVE_APP_NAME = "Xianjiapp.apk";
	public final static String SAVE_APP_LOCATION = "/download";

	public final static String APP_FILE_NAME = "/sdcard" + SAVE_APP_LOCATION
			+ File.separator + SAVE_APP_NAME;

	/**
	 * 下载Apk, 并设置Apk地址, 默认位置: /storage/sdcard0/Download
	 * 
	 * @param context
	 *            上下文
	 * @param downLoadUrl
	 *            下载地址
	 * @param description
	 *            通知描述
	 * @param name
	 *            通知名称
	 */
	@SuppressWarnings("unused")
	// public long enqueue(Request request) 执行下载，返回 downloadId，downloadId
	// 可用于后面查询下载信息。
	// 若网络不满足条件、Sdcard 挂载中、超过最大并发数等异常则会等待下载，正常则直接下载。
	public static long downloadApk(Context context, String downLoadUrl,
			String name, String description) {

		DownloadManager.Request request;

		if (!isDownloadManagerAvailable()) {
			return 0;
		}

		String appUrl = downLoadUrl;
		if (appUrl == null || appUrl.isEmpty()) {
			return 0;
		}
		appUrl = appUrl.trim(); // 去掉首尾空格
		if (!appUrl.startsWith("http")) {
			appUrl = "http://" + appUrl; // 添加Http信息
		}

		try {
			request = new DownloadManager.Request(Uri.parse(appUrl));
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
        Toast.makeText(context, "正在下载中....", Toast.LENGTH_SHORT).show();
		// 通知栏标题
		request.setTitle(name);
		// 通知栏内容
		request.setDescription(description);

		// 在通知栏显示下载进度
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			request.allowScanningByMediaScanner();
			// VISIBILITY_VISIBLE_NOTIFY_COMPLETED 当处于下载中状态和下载完成时状态，均在通知栏中显示
			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		}
		// 网络类型：//NETWORK_WIFI wifi网络
		request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
		// 保存到外部环境的共有目录
		request.setDestinationInExternalPublicDir(SAVE_APP_LOCATION,
				SAVE_APP_NAME);

		Context appContext = context.getApplicationContext();
		// 获取 DownloadManager 实例获取 DownloadManager 实例
		DownloadManager manager = (DownloadManager) appContext
				.getSystemService(Context.DOWNLOAD_SERVICE);
		// 进入下载队列
		return manager.enqueue(request);

	}

	/**
	 * @param context
	 * @param ids
	 */
	public static void removeEnqueue(Context context, long... ids) {
		DownloadManager manager = (DownloadManager) context
				.getApplicationContext().getSystemService(
						Context.DOWNLOAD_SERVICE);
		for (long id : ids) {
			if (id != 0) {
				manager.remove(id);
			}
		}
	}

	// 最小版本号大于9
	private static boolean isDownloadManagerAvailable() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
	}

	// 安装Apk
	public static void installApk(final Context context) {
		try {
			Intent i = new Intent(Intent.ACTION_VIEW);
			String filePath = DownloadManagerUtils.APP_FILE_NAME;
			if (!new File(filePath).exists()) {

				// Toast.makeText(context, "文件不存在!", Toast.LENGTH_SHORT).show();
                PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_XIANJI_APK_EXIST, 0);
				final long id = downloadApk(context, HomeFragment.URL,
						"APK更新", "更新包下载中...");
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						HomeFragment.queryDownloadManager(id, context);
					}
				}, 1000);

				return;
			}
			Uri fileUri;
			/**
			 * 7.0以后避免 Uri.fromFile报错
			 */
			  if (Build.VERSION.SDK_INT >= 24) {  
				  ////这一步很重要。给目标应用一个临时的授权。
				  i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
                  fileUri = FileProvider.getUriForFile(context,context.getPackageName() + ".FileProvider",  
                          new File(filePath));  
              } else {  
                  fileUri = Uri.fromFile(new File(filePath));  
                
              }  
			  i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.setDataAndType(fileUri,
					"application/vnd.android" + ".package-archive");
			
			context.startActivity(i);
		} catch (Exception e) {
			Log.e("TAG", "安装失败");
			e.printStackTrace();
		}
	}

}